package util;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.io.InputStream;
import java.util.Properties;

public class MongoDBUtil {
    /*
    设置客户端最大的连接数
    connectionsPerHost
    设置如果连接全部被占用，新线程需要等待连接释放时间的最长等待时间
    connectTimeout
    使用构造器获得一个Mongo的客户端配置参数对象
    options
    */
    //使用Mongo构造参数创建一个Mongo客户端对象
    private static final Properties prop = new Properties();
    private static MongoClient client;
    static {
        InputStream in = null;
        try {
            in = MongoDBUtil.class.getResourceAsStream("/mongo.properties");
            prop.load(in);
            //创建一个Mongo客户点参数拼接器
            MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
            //设置客户端最大的连接数
            builder.connectionsPerHost(Integer.parseInt(prop.getProperty("connectionsPerHost")));
            //设置如果连接全部被占用，新线程需要等待连接释放时间的最长等待时间
            builder.maxWaitTime(Integer.parseInt(prop.getProperty("maxWaitTime")));
            //设置每个连接连接Mongo服务器的最大延迟时间
            builder.connectTimeout(Integer.parseInt(prop.getProperty("connectTimeout")));
            //使用构造器获得一个Mongo的客户端配置参数对象
            MongoClientOptions options = builder.build();
            client = new MongoClient(new ServerAddress(prop.getProperty("ip"), Integer.parseInt(prop.getProperty("port"))),options);
        } catch (Exception e) {
            throw new RuntimeException("初始化Mongo客户配置文件异常", e);
        }
    }
    //获得Mongo的客户端
    public static MongoClient getClient() {
        return client;
    }
    //获得database
    public static MongoDatabase getDB(){
        MongoDatabase db = client.getDatabase(prop.getProperty("database"));
        return db;
    }
    //根据CollectionName获得Collection对象
    public static MongoCollection<Document> getCollection(String collectionName){
        MongoDatabase db = getDB();
        MongoCollection<Document> collection = db.getCollection(collectionName);
        return collection;
    }
}
